<?php
/**
 * Controller_Admin_Receipt
 *
 * Класс Controller_Admin_Receipt отвечает за обработку админских страниц приходов товара
 *
 * @author Mike
 */
class Controller_Admin_Receipt extends Controller_Admin {

	/**
	 * Выбор действия по URL
	 *
	 */
	public function action() {
		if(!User_Seance::isAdmin()) throw new Exception('', 403);
		switch ($this->arrRequest[2]) {
			case '':
				$this->actionReceiptsList();
				break;
			case 'add':
				if(!isset($_GET['product'])) $this->actionReceiptsList();
				$idProduct = Service_Escape::absolutelyEscapeString($_GET['product']);
				$objProduct = new Product($idProduct);
				if(!$objProduct->id) throw new Exception('', 404);
				$this->actionAdd($objProduct);
				break;
			default: throw new Exception('', 404);
		}
	}

	/**
	 * Выводит список приходов товаров
	 *
	 */
	public function actionReceiptsList() {
		$objReceipt = new Receipt();
		$arrReceipts = $objReceipt->find('all', array('select' => '`product_receipt`.*, `product`.`product_name`, `size`.`size_name`' , 'joins' => 'INNER JOIN `product` USING(`ID_product`) INNER JOIN `size` USING(`ID_size`)', 'order' => '`product_receipt`.`created_at` DESC'));

		$this->title = $this->pageHead = 'Поступления товаров';
		
		$this->showHeader();
			View_Receipt::showAdminList($arrReceipts);
		$this->showFooter();
	}
	
	/**
	 * Добавление поступления товара
	 *
	 * @param Product $objProduct - объекто продукта
	 */
	public function actionAdd(Product $objProduct) {
		if (isset($_POST['Receipt'])) {
			$objReceipt = new Receipt($_POST['Receipt']);
			if ($objReceipt->save()) User_Seance::moveTo(W_ADMIN . 'receipts');
		}
		else $objReceipt = new Receipt();
	
		$this->title = $this->pageHead = 'Поступление ' . $objProduct->getField('product_name');
			
		$this->showHeader();
			View_Receipt::showEditForm($objReceipt, $objProduct);
		$this->showFooter();
	}
}